package com.yz.android_baozou.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yz.android_baozou.R;
import com.yz.android_baozou.adapter.Search_RecyclerAdapter;
import com.yz.android_baozou.bean.RankBean;
import com.yz.android_baozou.decoration.SpacesItemDecoration;
import com.yz.android_baozou.helper.OkHttpClientHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static android.content.ContentValues.TAG;

/**
 * Created by Administrator on 2016/11/2.
 */

public class SearchFragment extends Fragment {
    @Bind(R.id.recyclerView_Serach_main)
    RecyclerView recyclerViewSerachMain;
    private Context mContext;
    //post请求的网址
    private String PATH_URL = "http://dailyapi.ibaozou.com/api/v31/documents/search";
    private RankBean rankBean;
    private List<RankBean.DataBean> mList_RankBean;
    private Search_RecyclerAdapter recyclerAdapter;
    //获得最后一个课件的item的下标
    private int mLastVisibleItemPosition = 0;
    private int page = 1;
    //用来携带请求字段
    private Map map = new HashMap();
    private boolean flag;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mList_RankBean = new ArrayList<>();
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_main, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //设置RecyclerView的中间的间距
        recyclerViewSerachMain.addItemDecoration(new SpacesItemDecoration(10));
        //使用线性布局管理器
        final LinearLayoutManager manager = new LinearLayoutManager(mContext);
        //设置RecyclerView的布局管理器
        recyclerViewSerachMain.setLayoutManager(manager);
        //设置RecyclerView固定行高
        recyclerViewSerachMain.setHasFixedSize(true);
        //创建适配器
        recyclerAdapter = new Search_RecyclerAdapter(mContext, mList_RankBean, recyclerViewSerachMain);
        //设置RecyclerView的适配器
        recyclerViewSerachMain.setAdapter(recyclerAdapter);
        //利用recyclerView的自带下拉刷新
        recyclerViewSerachMain.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //如果滚动状态是停止 同时 滚动到了最后
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItemPosition == recyclerAdapter.getItemCount() - 1) {
                    //当滚动到最后时 使页码加1 同时进行网络访问
                    page++;
                    map.put("page", page + "");
                    flag = false;
                    loadDataFromUrl();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //利用布局管理器获得获得最后一个可见的item下标
                mLastVisibleItemPosition = manager.findLastVisibleItemPosition();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public RankBean parseJsonToBean(String jsonString) {
        Gson gson = new Gson();
        return gson.fromJson(jsonString, new TypeToken<RankBean>() {
        }.getType());
    }

    //加载网络数据方法
    private void loadDataFromUrl() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (PATH_URL != null) {
                    String json = OkHttpClientHelper.postKeyValuePair(mContext, PATH_URL, map, "url_request");
                    //解析成实体类
                    rankBean = parseJsonToBean(json);
                    if (rankBean != null) {
                        mList_RankBean = rankBean.getData();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //根据flag 获取不同的刷新方法
                                if (flag) {
                                    recyclerAdapter.reloadRecyclerView(mList_RankBean, true);
                                } else {
                                    recyclerAdapter.reloadRecyclerView(mList_RankBean, false);
                                }
                            }
                        });
                    } else {
                        Toast.makeText(mContext, "No Extra Message", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        //获得自定义的菜单项
        inflater.inflate(R.menu.menu_search, menu);
        //实例化菜单item
        MenuItem menuItem = menu.findItem(R.id.action_search_main);
        //根据菜单编译器获得自己定义的SerchVIew
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        //searchView设置监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                final String key = query;
                //当点击搜索时将page页码设置为1
                page = 1;
                map.put("page", page + "");
                map.put("keyword", key);
                flag = true;
                loadDataFromUrl();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        super.onCreateOptionsMenu(menu, inflater);
    }

}
